<!-- 登录表单页面 -->
<script setup>
import { ref, computed, reactive } from "vue";
// import { Icon } from "@iconify/vue";
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { useLayoutThemeStore } from "@/store/layout/layoutTheme.js";
import { useUserStore } from "@/store/business/user.js";
import { useRouter } from "vue-router";
import { sendCode } from "@/utils/api";

const { t } = useI18n();
const layoutSetting = useLayoutThemeStore().layoutSetting;
const borderRadius = computed(() => layoutSetting.borderRadius);
const userStore = useUserStore();

const formState = ref({
  username: "13525158082",
  password: "123456",
  loginType: "account",
  agree: false,
  phone: "",
  captcha: "",
});

const iconLoading = ref(false);

const switchLoginType = () => {
  // formState.value.username = ''
  // formState.value.password = ''
  // 验证码重置
  clearInterval(countdownConfig.timerId);
  countdownConfig.isCountingDown = false;
  countdownConfig.seconds = 60; // 重置秒数
  formState.value.loginType =
    formState.value.loginType === "account" ? "phone" : "account";
};

const phoneRegex = /^1[3-9]\d{9}$/;
const gerCaptcha = () => {
  console.log(1111, "111-验证码");
  if (!formState.value.phone) {
    message.error(t("message.pleaseEnterPhone"));
    return;
  }
  if (!phoneRegex.test(formState.value.phone)) {
    message.error(t("message.invalidPhoneNumber"));
    return;
  }
  sendCode({
    phone: formState.value.phone,
  }).then((res) => {
    if (res.code === 200) {
      message.success(t("message.msg"));
    } else {
      message.error(res.msg);
    }
  });
  startCountdown();
};
// 验证码
const countdownConfig = reactive({
  seconds: 60,
  isCountingDown: false,
  timerId: null,
});
const startCountdown = () => {
  if (!countdownConfig.isCountingDown) {
    countdownConfig.isCountingDown = true;
    countdownConfig.timerId = setInterval(() => {
      if (countdownConfig.seconds > 0) {
        countdownConfig.seconds--;
      } else {
        clearInterval(countdownConfig.timerId);
        countdownConfig.isCountingDown = false;
        countdownConfig.seconds = 60; // 重置秒数
      }
    }, 1000);
  }
};

// 勾选校验
const checkAgreement = (rule, value) => {
  if (!value) {
    return Promise.reject(new Error(t("message.pleaseEnterAgree")));
  }
  return Promise.resolve();
};

const router = useRouter();
const onFinish = async (values) => {
  console.log("Success:", values), (iconLoading.value = true);

  // if (formState.value.loginType === 'phone') {
  //   // message.error(t('message.verifyCodeError'))
  //   formState.value.verifyCode = ''
  //   return
  // }

  userStore.login({
    username: formState.value.username,
    password: formState.value.password,
    phone: formState.value.phone,
    captcha: formState.value.captcha,
    loginType: formState.value.loginType,
    agree: formState.value.agree,
  });
  // await router.push("/signIn?type=selectType");
  // message.success(t("message.loginSuccess"));

  // 测试动态路由（在这里动态增加路由）
};

const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);
};
</script>

<template>
  <a-form :model="formState" @finish="onFinish" @finishFailed="onFinishFailed">
    <a-form-item
      name="username"
      v-if="formState.loginType === 'account'"
      :rules="[{ required: true, message: t('message.pleaseEnterUsername') }]"
    >
      <a-input
        v-model:value="formState.username"
        :placeholder="t('message.pleaseEnterUsername')"
      >
        <template #prefix>
          <UserOutlined />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      name="phone"
      v-if="formState.loginType === 'phone'"
      :rules="[{ required: true, message: t('message.pleaseEnterPhone') }]"
    >
      <a-input
        v-model:value="formState.phone"
        :placeholder="t('message.pleaseEnterPhone')"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      name="password"
      v-if="formState.loginType === 'account'"
      :rules="[{ required: true, message: t('message.pleaseEnterPassword') }]"
    >
      <a-input-password
        v-model:value="formState.password"
        :placeholder="t('message.pleaseEnterPassword')"
      >
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item
      name="captcha"
      v-if="formState.loginType === 'phone'"
      :rules="[{ required: true, message: t('message.pleaseEnterVerifyCode') }]"
    >
      <a-input
        v-model:value="formState.captcha"
        :placeholder="t('message.pleaseEnterVerifyCode')"
      >
        <template #suffix>
          <span @click="gerCaptcha" style="cursor: pointer; color: #31bc63">{{
            countdownConfig.seconds != 60 ? `${countdownConfig.seconds}秒` : "获取验证码"
          }}</span>
        </template>
      </a-input>
    </a-form-item>

    <a-form-item name="agree" :rules="[{ validator: checkAgreement, trigger: 'change' }]">
      <a-checkbox v-model:checked="formState.agree">
        <span style="font-size: 12px">
          我已阅读并同意百分网《<a href="/developer-agreement" class="login-tip"
            >开发者协议条款</a
          >》和《<a href="/privacy-policy" class="login-tip">隐私政策</a>》
        </span>
      </a-checkbox>
    </a-form-item>
    <a-form-item>
      <a-button class="w100%" type="primary" :loading="iconLoading" html-type="submit">
        {{ t("setting.login") }}
      </a-button>
    </a-form-item>
    <a-form-item style="text-align: center">
      <div class="login_mode">
        <span @click="switchLoginType" class="login-tip">
          {{ formState.loginType === "account" ? "验证码登录" : "密码登录" }}
        </span>
        <span type="link" class="login-tip" @click="() => router.push('/login?id=1')"
          >开发者注册</span
        >
      </div>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less">
.login-tip {
  font-size: 12px;
  text-align: center;
  color: #31bc63;
  cursor: pointer;
  font-style: normal;
}
.login_mode {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
